<template>
  <div class="scan-qrcode">
    <div class="qrcode-wrapper" v-loading="loading" :style="{width: props.size+'px',height: props.size+'px'}">
      <img class="qrcode" :src="qrcode ? qrcode : HomeQRCode" alt="登录二维码" @click="click"/>
      <div class="status-cover" v-if="isShowStatusCover" @click="click">
        <div>{{statusMessage}}</div>
      </div>
    </div>
    <div class="scan-tips" v-if="props.scanTips">
      {{props.scanTips}}
    </div>
  </div>
</template>

<script lang="ts" setup>
import * as QRCode from "qrcode";
import {ComputedRef} from "vue";
import HomeQRCode from "@/assets/login/home_qrcode.png";

const props = withDefaults(defineProps<{
  loading: boolean,
  qrcodeContent: string,
  statusCover: {
    type: 'info' | 'warning' | 'error',
    message: string
  } | string,
  scanTips: string,
  size?: number
}>(), {
  loading: true,
  qrcodeContent: 'HELLO',
  statusCover: '点击刷新',
  scanTips: '',
  size: 250
})
const {qrcodeContent} = toRefs(props)

const emits = defineEmits(['click'])

const qrcode = ref()
watch(qrcodeContent, (newValue) => {
  QRCode.toDataURL(newValue ?? '', {margin: 0}).then(val => {
    qrcode.value = val
  })
})

const isShowStatusCover: ComputedRef<boolean> = computed(() => {
  if (typeof props.statusCover === 'string' && props.statusCover) {
    return true
  }

  if (typeof props.statusCover === 'object' && props.statusCover.message) {
    return true
  }

  return false
})

const statusMessage: ComputedRef<string> = computed(() => {
  if (typeof props.statusCover === 'string') {
    return props.statusCover
  } else {
    return props.statusCover.message
  }
})

const click = () => {
  emits('click')
}

</script>

<style scoped lang="scss">

.scan-qrcode{
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qrcode-wrapper {
  width: 250px;
  height: 250px;
  background: white;
  border-radius: 15px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  cursor: pointer;

  .qrcode {
    width: 100%;
    height: 100%;
  }
}

.status-cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(230, 230, 230, 0.9);
  color: var(--el-color-error);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.scan-tips {
  color: rgba(0, 0, 0, 0.7);
  font-size: 16px;
  margin-top: 10px
}
</style>
